package com.scalar.chiptrack.commons.dao;

import com.scalar.ScalarException;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * User: Sujan Kumar Suppala
 * Date: Jan 16, 2009
 * Time: 3:16:03 PM
 */
public class ConfigurationDAO
{
    public static Properties getConfigurationProps ( DBTransaction dbTransaction ) throws ScalarException
    {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rset = null;
        Properties props = new Properties();
        try
        {
            if ( dbTransaction != null )
            {
                conn = dbTransaction.getConnection();
            }
            else
            {
                conn = DataSource.getConnection();
            }
            pstmt = conn.prepareStatement ( "SELECT PROPERTY_KEY, PROPERTY_VALUE FROM CONFIGURATION_TABLE");

            rset = pstmt.executeQuery();
            while ( rset.next() )
            {
                props.setProperty( rset.getString("PROPERTY_KEY"), rset.getString( "PROPERTY_VALUE" ));
            }
        }
        catch ( Exception e )
        {
            throw new ScalarException ( "Could not load DB Properties", e );
        }
        finally
        {
            if ( rset != null )
            {
                try { rset.close(); } catch ( SQLException ignore ) {}
            }
            if ( pstmt != null )
            {
                try { pstmt.close(); } catch ( SQLException ignore ) {}
            }
            if ( conn != null )
            {
                try { conn.close(); } catch ( SQLException ignore ) {}
            }
        }
        return props;
    }

}
